package com.vvv.shortlink.project.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 初始化限流配置
 */
@Component
public class SentinelRuleConfig implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        List<FlowRule> rules = new ArrayList<>();
        // 创建短链限流规则
        FlowRule createOrderRule = new FlowRule();
        createOrderRule.setResource("create_short-link");
        createOrderRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        createOrderRule.setCount(3); // 每秒只能有3次请求

        // 加载熔断限流规则
        rules.add(createOrderRule);
        FlowRuleManager.loadRules(rules);


        List<DegradeRule> degradeRules = new ArrayList<>();
        // 创建熔断降级规则
        DegradeRule degradeRule = new DegradeRule();
        degradeRule.setResource("create_short-link");  // 设置资源名，需要和流控规则使用相同的资源名
        degradeRule.setGrade(RuleConstant.DEGRADE_GRADE_RT);  // 基于响应时间来触发熔断
        degradeRule.setCount(500);  // 设置RT的阈值为500ms
        degradeRule.setTimeWindow(5);  // 设置熔断时长为5秒
        degradeRule.setMinRequestAmount(10);  // 设置最小请求数为10
        degradeRule.setStatIntervalMs(10000);  // 设置统计时间窗口为10000ms
        degradeRule.setSlowRatioThreshold(0.5);  // 设置慢调用比例阈值为0.5

        // 加载熔断降级规则
        degradeRules.add(degradeRule);
        DegradeRuleManager.loadRules(degradeRules);
    }
}